package com.xxx.topapplication;

import android.Manifest;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hdz
 * @date 2019/08/07
 */
public class MainActivity extends AppCompatActivity implements TopActivityListener.Callback, CompoundButton.OnCheckedChangeListener {

    private static final int PERMISSIONS_REQUEST_APPS_USAGE_ACCESS = 1102;
    private TopActivityListener topActivityListener;

    private boolean bWriteExternalStoragePermission = false;

    private Switch mSwitchOverlayWindowPermission;
    private Switch mSwitchUsageStatsPermission;

    private TextView mTextTag1;
    private TextView mTextTag2;

    private TextView mTipsText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        requesrPermission();
    }

    private void initView() {
        mTextTag1 = (TextView)findViewById(R.id.text_tag_1);
        mTextTag2 = (TextView)findViewById(R.id.text_tag_2);
        mTipsText = (TextView)findViewById(R.id.tips_text);

        mSwitchOverlayWindowPermission = (Switch)findViewById(R.id.switch_overlay_window_permission);
        mSwitchOverlayWindowPermission.setChecked(true);

        mSwitchUsageStatsPermission = (Switch)findViewById(R.id.switch_usage_stats_permission);
        mSwitchUsageStatsPermission.setChecked(true);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mSwitchUsageStatsPermission.setOnCheckedChangeListener(null);
        mSwitchOverlayWindowPermission.setOnCheckedChangeListener(null);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(this)) {
                mSwitchOverlayWindowPermission.setChecked(true);
            } else {
                mSwitchOverlayWindowPermission.setChecked(false);
            }
        } else {
            mSwitchOverlayWindowPermission.setChecked(true);
        }

        if (mSwitchOverlayWindowPermission.isChecked()) {
            mSwitchOverlayWindowPermission.setVisibility(View.INVISIBLE);
            mTextTag1.setVisibility(View.INVISIBLE);
        } else {
            mSwitchOverlayWindowPermission.setVisibility(View.VISIBLE);
            mTextTag1.setVisibility(View.VISIBLE);
        }


        if (hasAppsUsageAccessPermission()) {
            mSwitchUsageStatsPermission.setChecked(true);
        } else {
            mSwitchUsageStatsPermission.setChecked(false);
        }

        if (mSwitchUsageStatsPermission.isChecked()) {
            mSwitchUsageStatsPermission.setVisibility(View.INVISIBLE);
            mTextTag2.setVisibility(View.INVISIBLE);
        } else {
            mSwitchUsageStatsPermission.setVisibility(View.VISIBLE);
            mTextTag2.setVisibility(View.VISIBLE);
        }

        if (mSwitchOverlayWindowPermission.isChecked() && mSwitchUsageStatsPermission.isChecked()) {
            mTipsText.setVisibility(View.INVISIBLE);
        } else {
            mTipsText.setVisibility(View.VISIBLE);
        }

        if (topActivityListener == null) {
            if (mSwitchOverlayWindowPermission.isChecked() && mSwitchUsageStatsPermission.isChecked()) {
                topActivityListener = new TopActivityListener(this, this);
                startService(new Intent(MainActivity.this, FloatWindowService.class));
                moveTaskToBack(true);
            }
        }

        mSwitchUsageStatsPermission.setOnCheckedChangeListener(this);
        mSwitchOverlayWindowPermission.setOnCheckedChangeListener(this);
    }

    private boolean hasAppsUsageAccessPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            // 获取系统管理服务，即应用操作管理器
            AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
            // 权限检查
            int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), getPackageName());
            return mode == AppOpsManager.MODE_ALLOWED;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            bWriteExternalStoragePermission = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[i]);
                    if (showRequestPermission) {
                        //禁止后但没有勾选不再询问
                        if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            bWriteExternalStoragePermission = false;
                        }
                    } else {
                        //勾选不再询问并禁止
                        if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            bWriteExternalStoragePermission = false;
                        }
                    }
                }
            }
            if (!bWriteExternalStoragePermission) {
                requesrPermission();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (topActivityListener != null) {
            topActivityListener.release();
        }
        super.onDestroy();
    }


    private void requesrPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = new ArrayList<>();
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            } else {
                bWriteExternalStoragePermission = true;
            }
            if (permissionList.size() > 0) {
                String[] permissions = permissionList.toArray(new String[permissionList.size()]);//将List转为数组
                ActivityCompat.requestPermissions(this, permissions, 1);
            }
        }
    }


    @Override
    public void onCurrentApplicationChanged(final AppInfo appInfo) {
        Log.e("==", appInfo.getPackageName());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String apkPath = null;
                try {
                    apkPath = getPackageManager().getApplicationInfo(appInfo.getPackageName(), 0).sourceDir;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                Log.e("==", apkPath);
                FloatWindowManager.getInstance().setAppInfo(appInfo.getLogo(), appInfo.getName(), appInfo.getVersion(), appInfo.getPackageName(), appInfo.getApkPath());
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.switch_overlay_window_permission:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
                }
                break;
            case R.id.switch_usage_stats_permission:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    startActivityForResult(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS), PERMISSIONS_REQUEST_APPS_USAGE_ACCESS);
                    String s = getResources().getString(R.string.app_name);
                    Toast.makeText(MainActivity.this, "找到【"+s+"】并开启允许访问", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }
}
